#include "nextgen_placeholder.h"
#include <QJsonObject>
#include <QJsonDocument>
#include <QPainterPath>
#include <QFontMetrics>
#include <cmath>
// === 常量定义 ===
const QString NextGenPlaceholder::PLACEHOLDER_SIGNATURE = "NEXTGEN_PLACEHOLDER_V2";
const QString NextGenPlaceholder::METADATA_KEY = "PlaceholderMetadata";
const int NextGenPlaceholder::METADATA_VERSION = 2;
// 颜色主题定义
const QColor NextGenPlaceholder::LOADING_BG_COLOR(245, 245, 247);        // 淡灰色
const QColor NextGenPlaceholder::ERROR_BG_COLOR(254, 242, 242);          // 淡红色
const QColor NextGenPlaceholder::WAITING_BG_COLOR(254, 249, 195);        // 淡黄色
const QColor NextGenPlaceholder::PROCESSING_BG_COLOR(239, 246, 255);     // 淡蓝色
const QColor NextGenPlaceholder::CACHE_MISSING_BG_COLOR(248, 250, 252);  // 极淡灰
const QColor NextGenPlaceholder::LOADING_TEXT_COLOR(107, 114, 128);      // 中灰色
const QColor NextGenPlaceholder::ERROR_TEXT_COLOR(185, 28, 28);          // 深红色
const QColor NextGenPlaceholder::WAITING_TEXT_COLOR(180, 83, 9);         // 深橙色
const QColor NextGenPlaceholder::PROCESSING_TEXT_COLOR(29, 78, 216);     // 深蓝色
const QColor NextGenPlaceholder::CACHE_MISSING_TEXT_COLOR(75, 85, 99);   // 深灰色
// === 核心接口实现 ===
QImage NextGenPlaceholder::create(const QSize& size, State state, const QString& message)
{
    // 创建图像
    QImage image(size, QImage::Format_ARGB32);
    image.fill(Qt::transparent);
    // 创建绘制器
    QPainter painter(&image);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setRenderHint(QPainter::TextAntialiasing);
    QRect rect(0, 0, size.width(), size.height());
    // 根据状态绘制不同样式
    switch (state) {
        case LOADING:
            drawLoadingStyle(painter, rect, message.isEmpty() ? "加载中..." : message);
            break;
        case STATE_ERROR:
            drawErrorStyle(painter, rect, message.isEmpty() ? "加载失败" : message);
            break;
        case WAITING:
            drawWaitingStyle(painter, rect, message.isEmpty() ? "等待加载" : message);
            break;
        case PROCESSING:
            drawProcessingStyle(painter, rect, message.isEmpty() ? "处理中..." : message);
            break;
        case CACHE_MISSING:
            drawCacheMissingStyle(painter, rect, message.isEmpty() ? "缓存缺失" : message);
            break;
    }
    painter.end();
    // 内嵌元数据
    embedMetadata(image, state, message);
    return image;
}
bool NextGenPlaceholder::isPlaceholder(const QImage& image)
{
    if (image.isNull()) {
        return true;  // 空图像视为占位符
    }
    return hasMetadata(image);
}
bool NextGenPlaceholder::isRealContent(const QImage& image)
{
    return !isPlaceholder(image);
}
NextGenPlaceholder::State NextGenPlaceholder::getState(const QImage& image)
{
    if (!isPlaceholder(image)) {
        return LOADING;  // 默认状态
    }
    QString metadata = extractMetadata(image);
    if (metadata.isEmpty()) {
        return LOADING;
    }
    QJsonDocument doc = QJsonDocument::fromJson(metadata.toUtf8());
    QJsonObject obj = doc.object();
    int stateValue = obj["state"].toInt(0);
    return static_cast<State>(stateValue);
}
QString NextGenPlaceholder::getMessage(const QImage& image)
{
    if (!isPlaceholder(image)) {
        return QString();
    }
    QString metadata = extractMetadata(image);
    if (metadata.isEmpty()) {
        return QString();
    }
    QJsonDocument doc = QJsonDocument::fromJson(metadata.toUtf8());
    QJsonObject obj = doc.object();
    return obj["message"].toString();
}
// === 便捷方法实现 ===
QImage NextGenPlaceholder::createLoading(const QSize& size, const QString& message)
{
    return create(size, LOADING, message);
}
QImage NextGenPlaceholder::createError(const QSize& size, const QString& message)
{
    return create(size, STATE_ERROR, message);
}
QImage NextGenPlaceholder::createWaiting(const QSize& size, const QString& message)
{
    return create(size, WAITING, message);
}
QImage NextGenPlaceholder::createProcessing(const QSize& size, const QString& message)
{
    return create(size, PROCESSING, message);
}
QImage NextGenPlaceholder::createCacheMissing(const QSize& size, const QString& message)
{
    return create(size, CACHE_MISSING, message);
}
// === 调试接口实现 ===
QString NextGenPlaceholder::getImageInfo(const QImage& image)
{
    if (image.isNull()) {
        return "空图像";
    }
    bool placeholder = isPlaceholder(image);
    QString info = QString("尺寸: %1x%2, 格式: %3, 类型: %4")
                   .arg(image.width())
                   .arg(image.height())
                   .arg(image.format())
                   .arg(placeholder ? "占位符" : "真实内容");
    if (placeholder) {
        State state = getState(image);
        QString message = getMessage(image);
        QString stateNames[] = {"加载中", "错误", "等待", "处理中", "缓存缺失"};
        info += QString(", 状态: %1").arg(stateNames[state]);
        if (!message.isEmpty()) {
            info += QString(", 消息: %1").arg(message);
        }
    }
    return info;
}
QString NextGenPlaceholder::getPlaceholderInfo(const QImage& image)
{
    if (!isPlaceholder(image)) {
        return "非占位符图像";
    }
    State state = getState(image);
    QString message = getMessage(image);
    QString stateNames[] = {"LOADING", "ERROR", "WAITING", "PROCESSING", "CACHE_MISSING"};
    QString info = QString("占位符状态: %1").arg(stateNames[state]);
    if (!message.isEmpty()) {
        info += QString(", 消息: %1").arg(message);
    }
    return info;
}
// === 元数据管理实现 ===
void NextGenPlaceholder::embedMetadata(QImage& image, State state, const QString& message)
{
    // 创建元数据JSON
    QJsonObject metadata;
    metadata["signature"] = PLACEHOLDER_SIGNATURE;
    metadata["version"] = METADATA_VERSION;
    metadata["state"] = static_cast<int>(state);
    metadata["message"] = message;
    metadata["timestamp"] = QDateTime::currentMSecsSinceEpoch();
    QJsonDocument doc(metadata);
    QString metadataString = doc.toJson(QJsonDocument::Compact);
    // 将元数据嵌入图像
    image.setText(METADATA_KEY, metadataString);
}
QString NextGenPlaceholder::extractMetadata(const QImage& image)
{
    return image.text(METADATA_KEY);
}
bool NextGenPlaceholder::hasMetadata(const QImage& image)
{
    QString metadata = extractMetadata(image);
    if (metadata.isEmpty()) {
        return false;
    }
    // 验证元数据格式
    QJsonDocument doc = QJsonDocument::fromJson(metadata.toUtf8());
    if (doc.isNull()) {
        return false;
    }
    QJsonObject obj = doc.object();
    QString signature = obj["signature"].toString();
    int version = obj["version"].toInt(0);
    // 检查签名和版本
    return signature == PLACEHOLDER_SIGNATURE && version == METADATA_VERSION;
}
// === 视觉样式实现 ===
void NextGenPlaceholder::drawLoadingStyle(QPainter& painter, const QRect& rect, const QString& message)
{
    drawBackground(painter, rect, LOADING_BG_COLOR);
    // 计算图标和文本区域
    int iconSize = qMin(rect.width(), rect.height()) / 4;
    iconSize = qMax(24, qMin(iconSize, 64));
    QRect iconRect(rect.center().x() - iconSize/2, rect.center().y() - iconSize/2 - 20, iconSize, iconSize);
    QRect textRect(rect.left() + 10, iconRect.bottom() + 10, rect.width() - 20, 40);
    drawStateIcon(painter, iconRect, LOADING);
    drawMessage(painter, textRect, message, LOADING_TEXT_COLOR);
}
void NextGenPlaceholder::drawErrorStyle(QPainter& painter, const QRect& rect, const QString& message)
{
    drawBackground(painter, rect, ERROR_BG_COLOR);
    int iconSize = qMin(rect.width(), rect.height()) / 4;
    iconSize = qMax(24, qMin(iconSize, 64));
    QRect iconRect(rect.center().x() - iconSize/2, rect.center().y() - iconSize/2 - 20, iconSize, iconSize);
    QRect textRect(rect.left() + 10, iconRect.bottom() + 10, rect.width() - 20, 40);
    drawStateIcon(painter, iconRect, STATE_ERROR);
    drawMessage(painter, textRect, message, ERROR_TEXT_COLOR);
}
void NextGenPlaceholder::drawWaitingStyle(QPainter& painter, const QRect& rect, const QString& message)
{
    drawBackground(painter, rect, WAITING_BG_COLOR);
    int iconSize = qMin(rect.width(), rect.height()) / 4;
    iconSize = qMax(24, qMin(iconSize, 64));
    QRect iconRect(rect.center().x() - iconSize/2, rect.center().y() - iconSize/2 - 20, iconSize, iconSize);
    QRect textRect(rect.left() + 10, iconRect.bottom() + 10, rect.width() - 20, 40);
    drawStateIcon(painter, iconRect, WAITING);
    drawMessage(painter, textRect, message, WAITING_TEXT_COLOR);
}
void NextGenPlaceholder::drawProcessingStyle(QPainter& painter, const QRect& rect, const QString& message)
{
    drawBackground(painter, rect, PROCESSING_BG_COLOR);
    int iconSize = qMin(rect.width(), rect.height()) / 4;
    iconSize = qMax(24, qMin(iconSize, 64));
    QRect iconRect(rect.center().x() - iconSize/2, rect.center().y() - iconSize/2 - 20, iconSize, iconSize);
    QRect textRect(rect.left() + 10, iconRect.bottom() + 10, rect.width() - 20, 40);
    drawStateIcon(painter, iconRect, PROCESSING);
    drawMessage(painter, textRect, message, PROCESSING_TEXT_COLOR);
}
void NextGenPlaceholder::drawCacheMissingStyle(QPainter& painter, const QRect& rect, const QString& message)
{
    drawBackground(painter, rect, CACHE_MISSING_BG_COLOR);
    int iconSize = qMin(rect.width(), rect.height()) / 4;
    iconSize = qMax(24, qMin(iconSize, 64));
    QRect iconRect(rect.center().x() - iconSize/2, rect.center().y() - iconSize/2 - 20, iconSize, iconSize);
    QRect textRect(rect.left() + 10, iconRect.bottom() + 10, rect.width() - 20, 40);
    drawStateIcon(painter, iconRect, CACHE_MISSING);
    drawMessage(painter, textRect, message, CACHE_MISSING_TEXT_COLOR);
}
void NextGenPlaceholder::drawBackground(QPainter& painter, const QRect& rect, const QColor& bgColor)
{
    // 绘制圆角矩形背景
    int cornerRadius = qMin(rect.width(), rect.height()) / 20;
    cornerRadius = qMax(8, qMin(cornerRadius, 16));
    painter.setPen(Qt::NoPen);
    painter.setBrush(bgColor);
    painter.drawRoundedRect(rect, cornerRadius, cornerRadius);
    // 绘制边框
    painter.setPen(QPen(bgColor.darker(110), 1));
    painter.setBrush(Qt::NoBrush);
    painter.drawRoundedRect(rect, cornerRadius, cornerRadius);
}
void NextGenPlaceholder::drawStateIcon(QPainter& painter, const QRect& iconRect, State state)
{
    painter.setRenderHint(QPainter::Antialiasing);
    switch (state) {
        case LOADING:
            {
                // 绘制旋转的圆环
                painter.setPen(QPen(LOADING_TEXT_COLOR, 3));
                painter.setBrush(Qt::NoBrush);
                int startAngle = 0;
                int spanAngle = 270 * 16;  // Qt uses 1/16 degree units
                painter.drawArc(iconRect, startAngle, spanAngle);
            }
            break;
        case STATE_ERROR:
            {
                // 绘制叉号
                painter.setPen(QPen(ERROR_TEXT_COLOR, 3, Qt::SolidLine, Qt::RoundCap));
                int margin = iconRect.width() / 4;
                painter.drawLine(iconRect.left() + margin, iconRect.top() + margin,
                               iconRect.right() - margin, iconRect.bottom() - margin);
                painter.drawLine(iconRect.right() - margin, iconRect.top() + margin,
                               iconRect.left() + margin, iconRect.bottom() - margin);
            }
            break;
        case WAITING:
            {
                // 绘制时钟图标
                painter.setPen(QPen(WAITING_TEXT_COLOR, 2));
                painter.setBrush(Qt::NoBrush);
                painter.drawEllipse(iconRect);
                QPoint center = iconRect.center();
                int radius = iconRect.width() / 4;
                painter.drawLine(center, center + QPoint(0, -radius));  // 时针
                painter.drawLine(center, center + QPoint(radius/2, 0)); // 分针
            }
            break;
        case PROCESSING:
            {
                // 绘制齿轮图标
                painter.setPen(QPen(PROCESSING_TEXT_COLOR, 2));
                painter.setBrush(Qt::NoBrush);
                QPoint center = iconRect.center();
                int radius = iconRect.width() / 3;
                // 外圈齿轮
                for (int i = 0; i < 8; ++i) {
                    double angle = i * M_PI / 4;
                    QPoint outer(center.x() + radius * cos(angle), center.y() + radius * sin(angle));
                    QPoint inner(center.x() + (radius-6) * cos(angle), center.y() + (radius-6) * sin(angle));
                    painter.drawLine(inner, outer);
                }
                // 内圈
                painter.drawEllipse(center, radius-10, radius-10);
            }
            break;
        case CACHE_MISSING:
            {
                // 绘制文件夹图标
                painter.setPen(QPen(CACHE_MISSING_TEXT_COLOR, 2));
                painter.setBrush(Qt::NoBrush);
                int w = iconRect.width();
                int h = iconRect.height();
                QRect folderRect(iconRect.left() + w/6, iconRect.top() + h/4, w*2/3, h/2);
                painter.drawRect(folderRect);
                // 文件夹标签
                QRect tabRect(folderRect.left(), folderRect.top() - h/8, w/3, h/8);
                painter.drawRect(tabRect);
            }
            break;
    }
}
void NextGenPlaceholder::drawMessage(QPainter& painter, const QRect& textRect, const QString& message, const QColor& textColor)
{
    if (message.isEmpty() || textRect.height() < 20) {
        return;
    }
    painter.setPen(textColor);
    // 设置字体
    QFont font = painter.font();
    font.setPointSize(qMax(8, qMin(textRect.height() / 2, 14)));
    painter.setFont(font);
    // 绘制文本
    painter.drawText(textRect, Qt::AlignCenter | Qt::TextWordWrap, message);
}